package com.whfc.openapi.api.fse.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.whfc.common.constant.QueueConst;
import com.whfc.common.enums.DevicePlatform;
import com.whfc.common.result.Result;
import com.whfc.common.result.ResultUtil;
import com.whfc.common.third.zzkde.CrawlerData;
import com.whfc.common.third.zzkde.CrawlerDataUtil;
import com.whfc.common.util.DateUtil;
import com.whfc.common.util.JSONUtil;
import com.whfc.fse.dto.FseCrawlerDataDTO;
import com.whfc.fuum.dto.open.OpenApiClientDTO;
import com.whfc.openapi.constant.OpenApiConst;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * @Description: 履带吊实时数据接收(厂家 : 恺德尔科技)
 * @author: xugcheng
 * @version: 1.0
 * @date: 2021-10-19 10:09
 */
@RestController
@RequestMapping("/open/api/v1/fse/crawler")
public class FseCrawlerController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private AmqpTemplate amqpTemplate;

    @PostMapping("/data/add")
    public Result dataAdd(@RequestAttribute(OpenApiConst.OPENAPI_CLIENT) OpenApiClientDTO openApiClientDTO,
                          @RequestBody String body) {
        logger.info("开放平台新增履带吊实时数据,body：{}", body);

        // {"payload":"{\"src\":\"P*1*55*2*9903*1*2*18*5*47*5778*0*0*28382*500*0*8505*0*19*238*0*0*0*0*0*1*0*7790*1199*1636594492*1636594688*0*0*0*0*0*0*0*0*0*0*0*0*0*B*K\",\"time\":\"2021-11-11 09:32:17\"}"}
        JSONObject jsonObject = JSON.parseObject(body);
        JSONObject payload = jsonObject.getJSONObject("payload");
        if (payload != null) {
            String dataStr = payload.getString("src");
            String timeStr = payload.getString("time");
            Date time = DateUtil.parseDateTime(timeStr);
            if (StringUtils.isNotEmpty(dataStr)) {
                CrawlerData crawlerData = CrawlerDataUtil.parseCrawlerData(dataStr);
                crawlerData.setTime(time);
                FseCrawlerDataDTO fseCrawlerDataDTO = new FseCrawlerDataDTO();
                BeanUtils.copyProperties(crawlerData, fseCrawlerDataDTO);
                fseCrawlerDataDTO.setPlatform(DevicePlatform.kaierde.name());
                amqpTemplate.convertAndSend(QueueConst.FSE_CRAWLER_CURRENT_DATA, JSONUtil.toString(fseCrawlerDataDTO));
            }
        }

        return ResultUtil.success();
    }
}
